﻿using Kinlo.Entitys; 
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using XingLucifer.IBase.Enums;

namespace Kinlo.MESDocking
{
    /// <summary>
    /// 工单获取接口
    /// </summary>
    public class GetByProductCodeInterface : MESInteractionBase
    {
        /// <summary>
        /// 工单获取接口
        /// </summary>
        /// <param name="log"></param>
        /// <param name="dialog"></param>
        public GetByProductCodeInterface(Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog)
            : base(log, dialog, "工单获取接口")
        {
        }

        public override ResultTypes Interaction(string url, int timeout, int reconnect_count, DateTime dateTime, ProductionData[] production, Dictionary<string, object> parameters)
        {
            _stopwatch.Restart();
            string json = JsonSerializer.Serialize(parameters["parameter"], HttpHelper.Options);
            var result = Post(json, url, timeout, reconnect_count);
            _stopwatch.Stop();
            _log?.Invoke("", _name, result.Item2, json, result.Item1 ? "请求成功" : "请求异常",
                _stopwatch.ElapsedMilliseconds, dateTime, parameters["machineNo"]?.ToString() ?? "", parameters["producttype"].ToString() ?? "", this.GetType().Name, url);
            if (result.Item1)
            {
                var result_json = JsonSerializer.Deserialize<Dictionary<string,object>>(result.Item2);
                if (result_json["code"].ToString() != "200")
                {
                    _dialog?.Invoke(_name, result_json["code"].ToString(), result_json["errorMsg"].ToString());
                }
                else
                {
                    parameters.Clear();
                    parameters.Add("result", JsonSerializer.Deserialize<List<Dictionary<string, object>>>(result_json["data"].ToString()));
                    return ResultTypes.合格;
                }
            }
            else
            {
                _dialog?.Invoke(_name, "ERROR", result.Item2);
            }
            return ResultTypes.MES_NG;
        }
    }
}
